// 公共接口
import {
  request,
  getBaseUrl,
} from '../request';

import {
  sendLog, // 输出日志到本地
  viewLog, // 打印和输出日志到本地
  getEnvironmentType // 运行环境
} from '@/common/js/utils/index.js';

let upload_url = 'http://192.168.100.100:10002/upload';

// 上传接口
export const FileUploadPublic = (params) => {
  let baseUrl = upload_url || '';

  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: baseUrl,
      filePath: params.filePath,
      name: 'file', // 服务器端接收文件的字段名
      header: {
        'Referer': baseUrl,
        'X-Requested-With': 'XMLHttpRequest'
      },
      success: (res) => {
        console.log('上传成功1', res);
        resolve(res)
      },
      fail: (err) => {
        console.error('上传失败1', err);
        reject(err);
      }
    });
  })
}

// 选择上传图片
/* 
浏览器端的res
{
  "tempFilePaths": [
    "blob:http://localhost:5173/2ab254f1-15fd-413e-b0a0-2a4145b759a3"
  ],
  "tempFiles": [
    {}
  ],
  "errMsg": "chooseImage:ok"
}
plus-webview 中返回的res
{
  "res.tempFiles": {
    "tempFilePaths": [
      "blob:http://192.168.100.100:9001/76a2076a-7c2c-44e7-b9bd-6a345807fc03"
    ],
    "tempFiles": [
      {}
    ],
    "errMsg": "chooseImage:ok"
  }
}
*/
function getFileInfo(filePath) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', filePath, true);
    xhr.responseType = 'blob';
    xhr.onload = function() {
      if (this.status === 200) {
        const blob = this.response;
        const file = new File([blob], 'image.jpg', {
          type: blob.type,
        });
        resolve({
          path: filePath,
          size: file.size,
          type: file.type,
          name: file.name,
        });
      } else {
        reject(new Error('Failed to load file'));
      }
    };
    xhr.onerror = function() {
      reject(new Error('Failed to load file'));
    };
    xhr.send();
  });
}


/*

if (res.tempFilePaths && res.tempFilePaths.length > 0) {
          const tempFiles = [];

          // 遍历 tempFilePaths，获取文件信息
          for (const path of res.tempFilePaths) {
            try {
              const fileInfo = await getFileInfo(path);
              tempFiles.push(fileInfo);
            } catch (error) {
              console.error('获取文件信息失败', error);
            }
          }

          viewLog({
            tempFiles: tempFiles,
          });
          resolve(tempFiles);
        } else {
          resolve(res.tempFiles || []);
        }

*/

export const FileUploadImage = () => {
  return new Promise((resolve, reject) => {
    uni.chooseImage({
      count: 3,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['camera', 'album'], // 'album':相册
      success: async (res) => {
        console.log('选择图片', res);
        viewLog({
          'res': res,
        });

        resolve(res.tempFiles || []);
      },
      fail: (err) => {
        console.error('选择图片失败', err);
        reject(err);
      },
    });
  });
};

// 选择上传视频
export const FileUploadVideo = () => {
  return new Promise((resolve, reject) => {
    uni.chooseVideo({
      sourceType: ['camera'],
      maxDuration: 30,
      compressed: true,
      quality: 'medium', // 压缩质量:中
      success: (res) => {
        console.log(150, res);

        uni.showLoading({
          title: '上传中...',
          mask: true,
        });

        viewLog({
          'video_path': res.tempFilePath,
          'res': res
        })

        FileUploadPublic({
            filePath: res.tempFilePath
          })
          .then((res) => {
            if (res.statusCode === 200) {
              const backData = JSON.parse(res.data);
              if (backData.code === '0') {
                resolve(backData.data);
              } else {
                reject({
                  msg: 'video backData err',
                  res: res
                });
              }
            } else {
              reject({
                msg: 'video res err',
                res: res
              });
            }
          })
          .catch((err) => {
            reject(err);
          })
          .finally(() => {
            uni.hideLoading();
          });
      },
    });
  });
};


// 选择上传音频

// 数据字典
export const getDict = (params, otherObj) => {
  const data = Object.assign({}, {
    sepll: '',
    categoryType: '',
    number: 1000,
  }, params);
  let url = 'eis.simple?service=eamPageParamQueryService&method=getEamXmSelect';
  if (otherObj) {
    url = otherObj.url || url;
  }
  return request({
    url: url,
    isFormData: true,
    method: 'post',
    data: data
  })
}

// 数据字典--错误信息
export const getDictError = (params) => {
  const data = Object.assign({}, {
    sepll: '',
    number: 1000,
  }, params)
  return request({
    url: 'eis.simple?service=eamPageParamQueryService&method=getEamErrorInfoSelect',
    isFormData: true,
    method: 'post',
    data: data,
  })
}
// 数据字典--参数
export function getWorkParam(data) {
  return request({
    url: 'eis.simple?service=eamPageParamQueryService&method=queryAssetParamXmSelected',
    method: 'post',
    isFormData: true,
    data: data
  });
}
// 数据字典--物料名称
export function getMaterialName(data) {
  return request({
    // url: 'eis.simple?service=eamPageParamQueryService&method=queryMaterialsXmSelected',
    url: 'eis.simple?service=eamPageParamQueryService&method=queryMobileMaterialsXmSelected',
    method: 'post',
    isFormData: true,
    data: data
  });
}

// 选择人员
export const getPerson = (data) => {
  return request({
    url: 'eis.simple?service=pageParamQueryService&method=searchusercode',
    method: 'post',
    isFormData: true,
    data: data
  });
}

// 扫码
export const scanCodeAsset = (data) => {
  return request({
    url: 'eis.simple?service=eamOrderService&method=queryAssetByScan',
    method: 'post',
    // isFormData: true,
    data: data
  });
}